//
//  ModelSelectionViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 3/21/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "ModelSelectionViewController.h"
#import "ModelSelectionNavViewController.h"
#import "EditItemDetailViewController.h"
#import "AddNewModelViewController.h"
#import "Model.h"
#import "Item.h"

@interface ModelSelectionViewController () {
    
    /* xml */
	NSURL* url;
	NSMutableData* requestData;
	NSMutableString* theData;
	NSXMLParser* fileParser;
	Model *temp;
	BOOL noNetwork;
    
}

@end

@implementation ModelSelectionViewController

@synthesize delegate,selected,models;

-(IBAction)doneButton:(id)sender {
    
    // set the info for theItem - no need to upload now, that will happen after the done button
    [[delegate theItem] setMid:[selected modelId]];
    [[delegate theItem] setModel:[selected name]];
    
    // dismiss the popover
    [delegate goAway];
}

-(BOOL)refreshXML:(id)sender{
    
    self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refreshing data..."];
    
    noNetwork = NO;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    // drop the patrons array
    models = nil;
	models = [[NSMutableArray alloc] init];
    
    // get data from internet
    NSString *urlstring = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/listModelsForType.php?secret=pass&id=%i",[[[self.delegate theItem] myType] typeId]];

    url = [[NSURL alloc] initWithString:urlstring];
	NSURLRequest *dataRequest = [NSURLRequest requestWithURL:url
												 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
											 timeoutInterval:60];
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:dataRequest delegate:self];
	if (connection) {
		NSLog(@"refreshXML: Created connection request.");
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MMM d, h:mm a"];
        NSString *lastUpdated = [NSString stringWithFormat:@"Last updated on %@",[formatter stringFromDate:[NSDate date]]];
        self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
        [self.refreshControl endRefreshing];
        
        return true;
	}
	else {
		NSLog(@"refreshXML: ERROR: Could not create connection request.");
		//Output no internet
        return false;
	}
	
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setDelegate:self.navigationController];
    
    // allow pull down for refresh
    UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [refresh addTarget:self action:@selector(refreshXML:) forControlEvents:UIControlEventValueChanged];
    self.refreshControl = refresh;
    
    [self refreshXML:nil];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    NSLog(@"Returning num models: %i",[models count]);
    return [models count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SelectModelCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    
    cell.textLabel.text = [[models objectAtIndex:indexPath.row] name];
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self setSelected:[models objectAtIndex:indexPath.row]];
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    AddNewModelViewController *nextController = segue.destinationViewController;
    [nextController setInType:[[[delegate theItem] myType] typeId]];
    [nextController setDelegate:self];
    
}

/********************************************************************
 for xml parsing
 ********************************************************************/

//connection finished loading it's data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	// DEBUGGING: NSLog(@"GRABBED DATA%@", requestData);
    if (requestData) {
        NSLog(@"connectionDidFinishLoading: Retrieved XML data. Beginning XML parsing process.");
    } else {
        NSLog(@"connectionDidFinishLoading: ERROR: No XML data retrieved.");
    }
	//allocate file parser
	fileParser = [[NSXMLParser alloc] initWithData:requestData];
	
	//set current object as delegate
	[fileParser setDelegate:self];
	//start parsing
	[fileParser parse];
    NSLog(@"connectionDidFinishLoading: Ending XML parsing process");
    fileParser = nil;
	
	
}


//Connection failed
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"\t\tconnection DidFailWithError: ERROR: Connection failed, trigger notification.");
	//Connection failed, tell the user
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unable to connect." message:@"Your device is unable to connect to the network. Please check your network connection and try again." delegate:self cancelButtonTitle:@"Dismiss"  otherButtonTitles:nil, nil];
	[alert show];
	alert = nil;
	noNetwork = YES;
	[self.tableView reloadData];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
}
//Connection Started
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	//allocate a place to store the data until it is whole
	requestData = [[NSMutableData alloc] init];
	[requestData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	//Append data
	[requestData appendData:data];
}
//Found start tag
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
	if ([elementName isEqual:@"xml"]) {
		//Allocate a string that will hold the data
		theData = [[NSMutableString alloc] init];
	}
	else if ([elementName isEqual:@"model"]) {
		//allocate a temporary variable to hold the data until it is ready to be stored in the array
		temp = [[Model alloc] init];
	}
	if (![elementName isEqual:@"xml"]) {
		//black the string
		[theData setString:@""];
	}
}
//Found end tag while parsing
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	//Check the end element name and store it in theData to the appropriate variable
	if ([elementName isEqual:@"xml"]) {
        
	} else if ([elementName isEqual:@"id"]) {
		[temp setModelId:[theData integerValue]];
	} else if ([elementName isEqual:@"name"]) {
		[temp setName:[[NSString alloc] initWithString:theData]];
    } else if ([elementName isEqual:@"model"]) {
        NSLog(@"\t\tparser didEndElement: Retrieved Model with name %@",[temp name]);
		[models addObject:temp];
		temp = nil;
	}
	
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
	[theData appendString:string];
}

- (void)parserDidEndDocument:(NSXMLParser *)parse
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSLog(@"\t\tparserDidEndDocument: Data retrieved, reloading table.");
	[self.tableView reloadData];
}

@end
